package com.whzykj.resource;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DateUtil;
import com.whzykj.common.DbUtil;
import com.whzykj.common.JsonUtil;
import com.whzykj.common.ReturnEnum;
import com.whzykj.model.Account;
import com.whzykj.model.OrderInfo;

import net.sf.json.JSONObject;

public class PayResource {
	
	/****
	 * 付款交易接口
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'pay',type:'pay',user_id:'68',order_id:'APP20160724062217310'}
	 */
	public void pay(JSONObject messageObj, JSONObject result) {
		
		String user_id=messageObj.getString("user_id");//手机号
		String order_id=messageObj.getString("order_id");//手机号
		
		List<String> sqlList=new ArrayList<String>();						// 保存SQL语句
		
		String sql=" SELECT * FROM orderinfo r where r.STATUS='no_pay' and r.user_id="+user_id+" and r.order_id='"+order_id+"' ";
		OrderInfo order = OrderInfo.me.findFirst(sql);
		if(order == null)
		{
			JsonUtil.put(result, ReturnEnum.NO_PAY_ORDER);
			return;
		}else{
			//实付金额
			BigDecimal pay_amounts = order.getBigDecimal("pay_amounts");
			//客户ID
			int custid = order.getInt("cust_id");			
			String acctsql=" SELECT * FROM account WHERE cust_id=? ";
			Account acct = Account.dao.findFirst(acctsql, custid);
			//判断账户是否存在
			if(acct == null)
			{
				JsonUtil.put(result, ReturnEnum.NO_ACCT);
				return;
			}else{
				String state = acct.getStr("state");
				if("01".equals(state))//冻结
				{
					JsonUtil.put(result, ReturnEnum.NO_ACCT_FREEZE);
					return;
				}else if("02".equals(state)){//注销
					JsonUtil.put(result, ReturnEnum.NO_ACCT_CLOSE);
					return;
				}else{
					//账户总余额
					BigDecimal amount = acct.getBigDecimal("amount");
					int count=amount.compareTo(BigDecimal.ZERO); 
					//判断余额
					if(count == 0){
						JsonUtil.put(result, ReturnEnum.NO_ACCT_BALANCE);
						return;
					}
					// pay_amounts 实付金额       amount 账户总金额
					int count1=pay_amounts.compareTo(amount); 
					if(count1 == 1){
						JsonUtil.put(result, ReturnEnum.NO_ACCT_BALANCECOM);
						return;
					}else{
						BigDecimal balance = amount.subtract(pay_amounts);//减去支付金额后剩余余额
						/***
						 * ii.	添加记录到账户资金变动流水表Account_Seq中；
                           iii.	添加支付流水到本表（PayBill）中;
                           iv.	更改订单表（Orderinfo）中对应订单的状态。
						 */
						int acct_id = acct.getInt("acct_id");//账户ID
						
						String paySN= CommonUtils.generatePayBillSeq();
						String acctseqsn=CommonUtils.generateAcctSeq();
						String pay_check_state="00";//未对帐
						String pay_state = "00"; //00 - 支付成功； 01 - 撤销订单
						String pay_person = "00";//00 - 客户；01 - 站长（需要记录是客户自身支付，还是站长代为支付）
						
						StringBuffer sb=new StringBuffer(" insert into paybill(SN,acct_id,order_id,amount,pay_person,create_time,pay_check_state,pay_state ) ");
						sb.append(" values ('"+paySN+"',"+acct_id+",'"+order_id+"',"+pay_amounts+",'"+pay_person+"',now(),'"+pay_check_state+"', '"+pay_state+"' ");
						sb.append(" ) ");
						
						
						String seq_flag = "01";//入帐
						String change_type = "07";//00 - 虚拟充值； 01 -  线下充值； 02 - 支付宝充值； 03 - 微信充值； 04 - 银联充值；05 - 活动充值； 06 - 代金券充值； 07 -  支付； 08 - 提现； 09 - 撤销交易； 10 - 内部调账； 11 - 退赔
						// Account_Seq 主键生成
						StringBuffer sb0=new StringBuffer(" INSERT INTO  Account_Seq(SN,acct_id,seq_flag,change_type,pre_amount,amount,ref_sn,create_time)VALUES('");
						sb0.append( acctseqsn+"',"+acct_id+",'"+seq_flag+"','"+change_type+"',"+amount+","+balance+",'"+paySN+"',now()) ");
						
                        //更新订单状态
						StringBuffer sb1=new StringBuffer(" UPDATE orderinfo SET STATUS='nosend' WHERE ORDER_ID='"+order_id+"' ");
                        
						StringBuffer sb2= new StringBuffer();
						sb2.append(" update account set last_update_time=now(),last_update_person="+user_id+",amount="+balance+" where acct_id="+acct_id+" ");
						
						sqlList.add(sb.toString());
						sqlList.add(sb0.toString());
						sqlList.add(sb1.toString());
						sqlList.add(sb2.toString());
						/*****
						 * 入库
						 */
//						int[] cnts=Db.batch(sqlList, sqlList.size());
						boolean res=DbUtil.batch(sqlList);
						JsonUtil.put(result, ReturnEnum.PAY_SUCCESS);
					}
				}
			}
			
		}
	}
}
